import Controller from "../Controller";
import {Request,Response} from 'express';
import PageJson from "../../utils/PageJson";
import path from 'path'
import Fs from 'fs-extra'
import Config from "../../Config";
/**
 * 页面配置
 */
class Pages extends Controller
{
    // 模板id
    tpl_id:number = 0;

    constructor(req:Request,res:Response) {
        super(req,res);
        this.tpl_id = this.HD.tpl_id;
    }

    /**
     * 获取全局配置  配置文件page.json
     */
    async get() {
        const {dir} = await this.first("tpl",{
            id: this.tpl_id
        }) as { dir:string }
        const pages = PageJson.get(dir,"pages")
        let page = pages.find((page:any) => {
            return page.path == this.HD.path
        })
        this.response(200,page ? page.style : {})
    }

    /**
     * 提交生成配置文件page.json
     */
    async submit() {
        // 获取模板信息
        const { dir } = await this.first("tpl",{
            id: this.tpl_id
        }) as { dir:string }
        const data = PageJson.get(dir,"pages") 
        for(let i=0;i<data.length;i++) {
            if(data[i].path == this.HD.path) {
                data[i].style = this.HD.data
                break;
            }
        }
        PageJson.submit(dir,"pages",data)
        this.setBackground(dir,this.HD.data.backgroundColor,this.HD.path)
        this.response(200) 
    }

    /**
     * 设置页面背景颜色
     * @param dir 项目目录
     * @param color 背景颜色十六进制颜色
     * @param path_dir 页面路径
     */
    setBackground(dir:string,color:string,path_dir:string) {
        let filename = path.join(Config.data_dir,dir,"src",path_dir + '.vue')
        let page_content = Fs.readFileSync(filename,"utf-8")
        page_content = page_content.replace(/page\{background-color: .+;\}/,`page{background-color: ${color};}`)
        Fs.writeFileSync(filename,page_content,"utf-8")
    }
}

export default Pages;